import { useRef } from "react";

class Store {
      constructor() {
            this.store = {
                  username: "1213",
                  password: "12123",
            };

            this.watcherUpdateCb = {};
            this.validateCbMap = {};
      }

      setWatcherUpdate(_this) {
            let key = _this.props.name;
            this.watcherUpdateCb[key] = _this;

            return () => {
                  delete this.watcherUpdateCb[key];
            };
      }

      // 校验规则订阅，取消订阅
      setValidateWatcher(key, fn) {
            // 取消订阅
      }

      // 所有校验
      validateData() {
            
      }

      getStoreByKey(key) {
            return this.store[key];
      }

      getStore() {
            return this.store;
      }

      setStore(key, newValue) {
            this.store = {
                  ...this.store,
                  ...{[key]: newValue},
            };

            this.watcherUpdateCb[key] && this.watcherUpdateCb[key].renderInfo();
      }
}

export default function useForm({ form }) {
      const formData = useRef();
      // 先判断外面是否传入form
      if (form) {
            formData.current = form;
      } else if (!formData.current) {
            // 判断当前formData是否有值
            formData.current = new Store();
      }

      return [formData.current];
}
